package main

import (
	"fmt"
	"sync"
	"time"
)

//RWMutex是读/写互斥锁。锁可以由任意数量的读者或单个写者持有。 RWMutex的零值是未锁定的互斥锁
//func (rw *RWMutex) Lock         // Lock locks rw for writing.
//func (rw *RWMutex) RLock        // RLock locks rw for reading.
//func (rw *RWMutex) RUnlock      // Unlock locks rw for reading
//func (rw *RWMutex) Unlock       // Unlock unlocks rw for writing

var mu sync.RWMutex
var data map[string]string

func main() {
	data = map[string]string{"AA": "BBBB"}
	mu = sync.RWMutex{}
	go read()  // 程序运行时，获取读锁，2s释放读锁
	go write() // 3s后赋值，打印
	go read()  // 2s后获取读锁，读取数据
	time.Sleep(5 * time.Second)
}

// 读方法
func read() {
	println("read_start", "time", time.Now().Unix())
	mu.RLock()
	defer func() {
		fmt.Println("runlock ~~~", "time", time.Now().Unix())
		mu.RUnlock()
	}()
	time.Sleep(1 * time.Second)
	println("read_complete", data["AA"], "time", time.Now().Unix())
}

// 写方法
func write() {
	println("write_start", "time", time.Now().Unix())
	//mu.Lock()      // 仔细看下这两行代码,此处是注释掉的
	//defer mu.Unlock()
	time.Sleep(2 * time.Second)
	data["AA"] = "cccccccc"
	println("write_complete", data["AA"], "time", time.Now().Unix())
}


